#pragma once
#include <iostream>
#include <vector>
#include <assert.h>

namespace jc
{
	template<class T>
	class vector
	{
	public:
		typedef T* iterator;
		typedef const T* const_iterator;
		
		vector()
			:_start(nullptr)
			,_finish(nullptr)
			,_end_of_storage(nullptr)
		{

		}

		~vector()
		{
			if (_start )
			{
				delete[]_start;
				_start = _finish = _end_of_storage = nullptr;
			}
		}

		T& operator[](size_t i)
		{
			return _start[i];
		}

		T& operator[](size_t i) const
		{
			return _start[i];
		}

		iterator begin()
		{
			return _start;
		}
		const_iterator begin() const
		{
			return _start;
		}

		iterator end()
		{
			return _finish;
		}
		const_iterator end() const
		{
			return _finish;
		}

		size_t size() const
		{
			return _finish - _start;
		}

		size_t capacity() const
		{
			return _end_of_storage - _start;
		}

		void reserve(size_t n)
		{
			if (n > _end_of_storage - _start)
			{
				size_t oldsize = _finish - _start;
				iterator tmp = new T[n];
				if (_start)
				{
					memcpy(tmp, _start, sizeof(T) * oldsize);
					delete[]_start;	
				}
				_start = tmp;
				_finish = _start + oldsize;
				_end_of_storage = _start + n;
			}
		}

		void push_back(T x)
		{
			if (_finish == _end_of_storage)
			{
				reserve(capacity() == 0 ? 4 : 2 * capacity());
			}
			*_finish = x;
			_finish++;
		}

		bool empty()
		{
			return _finish == _start;
		}

		void pop_back()
		{
			assert(!empty());
			_finish--;
			
		}

		void insert(iterator pos,const T& c)
		{
			assert(pos >= _start && pos < _finish);
			if (_finish == _end_of_storage)
			{
				size_t len = pos - _start;
				reserve(capacity() == 0 ? 4 : 2 * capacity());
				pos = _start + len;
			}
			iterator end = _finish;
			while (end > pos)
			{
				*(end) = *(end-1);
				end--;
			}
			*end = c;
			_finish++;
		}

		void erase(iterator pos)
		{
			assert(!empty());
			iterator cur = pos;
			while (cur < _finish)
			{
				*cur = *(cur + 1);
				cur++;
			}
			_finish--;
		}

	private:
		iterator _start;
		iterator _finish;
		iterator _end_of_storage;
	};
}
